// 显示所有图书
function showAllBooks() {
    $.get('/api/library/books', function(books) {
        let html = `
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>状态</th>
                        <th>书名</th>
                        <th>作者</th>
                        <th>ISBN</th>
                    </tr>
                </thead>
                <tbody>
        `;
        
        books.forEach(book => {
            html += `
                <tr>
                    <td>${book.id}</td>
                    <td class="${book.available ? 'book-status-available' : 'book-status-borrowed'}">
                        ${book.available ? '可借' : '已借出'}
                    </td>
                    <td>${book.title}</td>
                    <td>${book.author}</td>
                    <td>${book.isbn}</td>
                </tr>
            `;
        });
        
        html += '</tbody></table>';
        $('#contentArea').html(html);
    });
}

// 显示借阅记录
function showBorrowRecords() {
    $.get('/api/library/records', function(records) {
        let html = `
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>记录ID</th>
                        <th>图书</th>
                        <th>借阅人</th>
                        <th>借阅时间</th>
                        <th>状态</th>
                    </tr>
                </thead>
                <tbody>
        `;
        
        records.forEach(record => {
            html += `
                <tr>
                    <td>${record.id}</td>
                    <td>${record.book.title}</td>
                    <td>${record.user.name}</td>
                    <td>${record.borrowDate}</td>
                    <td>${record.returned ? '已还' : '借出'}</td>
                </tr>
            `;
        });
        
        html += '</tbody></table>';
        $('#contentArea').html(html);
    });
}

// 借书
function borrowBook() {
    const bookId = $('#borrowBookId').val();
    const userId = $('#borrowUserId').val();
    
    $.post('/api/library/borrow', { bookId, userId })
        .done(function(success) {
            alert(success ? '借书成功！' : '借书失败！');
            $('#borrowModal').modal('hide');
            showAllBooks();
        })
        .fail(function() {
            alert('借书失败！');
        });
}

// 还书
function returnBook() {
    const borrowRecordId = $('#returnRecordId').val();
    
    $.post(`/api/library/return/${borrowRecordId}`)
        .done(function() {
            alert('还书成功！');
            $('#returnModal').modal('hide');
            showBorrowRecords();
        })
        .fail(function(jqXHR) {
            alert('还书失败：' + jqXHR.responseText);
        });
}

// 备份数据库
function backupDatabase() {
    const description = $('#backupDescription').val();

    // 先显示当前数据库状态
    showDatabaseStatus('备份前数据库状态').then(() => {
        $.post('/api/library/backup', { description: description })
            .done(function(fileName) {
                alert('数据库备份成功！');
                // 触发下载
                window.location.href = `/api/library/backup/download/${fileName}`;
                $('#backupModal').modal('hide');
                showBackupRecords();
            })
            .fail(function(jqXHR) {
                alert('数据库备份失败：' + jqXHR.responseText);
            });
    });
}

// 当还原模态框打开时显示备份记录
$('#restoreModal').on('show.bs.modal', function () {
    showBackupRecords();
});

// 显示备份记录
function showBackupRecords() {
    $.get('/api/library/backups', function(records) {
        let html = `
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>备份时间</th>
                        <th>备份说明</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
        `;
        
        records.forEach(record => {
            // 格式化备份时间为文件名格式
            const timestamp = record.backupDate.replace(/[^0-9]/g, '');
            const fileName = `backup_${timestamp}.sql`;
            html += `
                <tr>
                    <td>${record.id}</td>
                    <td>${record.backupDate}</td>
                    <td>${record.description || '-'}</td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="restoreBackup(${record.id})">还原</button>
                        <a href="/api/library/backup/download/${fileName}" 
                           class="btn btn-sm btn-secondary" 
                           target="_blank">下载</a>
                    </td>
                </tr>
            `;
        });
        
        html += '</tbody></table>';
        $('#contentArea').html(html);
        $('#backupRecordsList').html(html);  // 同时更新模态框中的列表
    });
}

function restoreBackup(backupId) {
    if (confirm('确定要还原此备份吗？这将覆盖当前数据库！')) {
        // 先显示还原前状态
        showDatabaseStatus('还原前数据库状态').then(() => {
            $.post('/api/library/restore', { backupId: backupId })
                .done(function() {
                    alert('数据库还原成功！');
                    $('#restoreModal').modal('hide');
                    // 显示还原后状态
                    showDatabaseStatus('还原后数据库状态').then(() => {
                        showBackupRecords();
                    });
                })
                .fail(function(jqXHR) {
                    alert('数据库还原失败：' + jqXHR.responseText);
                });
        });
    }
}

// 显示数据库状态
async function showDatabaseStatus(title) {
    let html = `<h3 class="text-center">${title}</h3>`;
    
    // 获取图书信息
    const books = await $.get('/api/library/books');
    html += `
        <h4>图书信息：</h4>
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>状态</th>
                    <th>书名</th>
                    <th>作者</th>
                    <th>ISBN</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    books.forEach(book => {
        html += `
            <tr>
                <td>${book.id}</td>
                <td class="${book.available ? 'book-status-available' : 'book-status-borrowed'}">
                    ${book.available ? '可借' : '已借出'}
                </td>
                <td>${book.title}</td>
                <td>${book.author}</td>
                <td>${book.isbn}</td>
            </tr>
        `;
    });
    html += '</tbody></table>';

    // 获取借阅记录
    const records = await $.get('/api/library/records');
    html += `
        <h4>借阅记录：</h4>
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>记录ID</th>
                    <th>图书</th>
                    <th>借阅人</th>
                    <th>借阅时间</th>
                    <th>状态</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    records.forEach(record => {
        html += `
            <tr>
                <td>${record.id}</td>
                <td>${record.book.title}</td>
                <td>${record.user.name}</td>
                <td>${record.borrowDate}</td>
                <td>${record.returned ? '已还' : '借出'}</td>
            </tr>
        `;
    });
    html += '</tbody></table>';

    $('#contentArea').html(html);
}

// 页面加载完成后显示所有图书
$(document).ready(function() {
    showAllBooks();
}); 